<template>
  <div class="app-container" style="grid-template-columns: auto;">
    <div class="topToolbar">
<!--      <div class="searchBar">-->
<!--        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">-->
<!--          <el-form-item  prop="userId">-->
<!--            <el-input-->
<!--              v-model="queryParams.userId"-->
<!--              placeholder="请输入人员id"-->
<!--              clearable-->
<!--              @keyup.enter.native="handleQuery"-->
<!--            />-->
<!--          </el-form-item>-->
<!--          <el-form-item>-->
<!--            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>-->
<!--            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>-->
<!--          </el-form-item>-->
<!--        </el-form>-->
<!--      </div>-->
    </div>

    <div class="main">
      <div class="main2">

        <div class="ToolBar">
          <div class="modNameBox">
            <div class="lump"></div>
            <span>工作日志-列表</span>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px" class="datePicker">
              <el-form-item prop="dateArray">
                <el-date-picker clearable
                                v-model="queryParams.dateArray"
                                unlink-panels
                                value-format="yyyy-MM-dd"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                :picker-options="executeTimeOptions"
                @change="getList">
                  >
                </el-date-picker>
              </el-form-item>
            </el-form>
          </div>

          <div class="topToolbar">
            <div class="ActionBar" style="min-width: 90px;">
            <el-button icon="el-icon-refresh-right" @click="$tab.refreshPage($route);"></el-button>
            <el-button plain icon="el-icon-plus" size="mini" @click="handleAdd"
                       v-hasPermi="['stage:construct:add']">新增</el-button>
<!--            <el-button plain icon="el-icon-edit" size="mini" @click="handleUpdate"-->
<!--                       v-hasPermi="['stage:construct:edit']">修改</el-button>-->
<!--            <el-button plain icon="el-icon-delete" size="mini" @click="handleDelete"-->
<!--                       v-hasPermi="['stage:construct:remove']">删除</el-button>-->
<!--            <el-button plain icon="el-icon-download" size="mini"-->
<!--                       @click="handleExport" v-hasPermi="['stage:construct:export']">导出-->
<!--            </el-button>-->
          </div>
          </div>
        </div>

        <div class="mainContent">
          <!--表格-->
          <div id="PrintMainTable" ref="PrintMainTable" style="height: calc(100% - 117px);margin-top: 20px;">
            <el-table v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" :data="constructionList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center"/>
              <el-table-column type="index" width="50" label="序号">
                <template slot-scope="scope">
                  <span v-text="indexMethods(scope.$index)"></span>
                </template>
              </el-table-column>
              <el-table-column label="日期" align="center" prop="constructDate" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.constructDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="人员" align="center" prop="userName" :show-overflow-tooltip="true"/>
              <el-table-column label="工作内容" align="center" prop="constructContent" :show-overflow-tooltip="true"/>
              <el-table-column label="遇到的问题及建议" align="center" prop="advice" :show-overflow-tooltip="true"/>
              <el-table-column label="今日耗时(h)" align="center" prop="timeConsume" :formatter="addUnit"/>
              <el-table-column label="操作" width="200" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <div class="link-type">
                    <span @click="handleSee(scope.row)">查看</span>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <pagination1
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>

      </div>
    </div>

    <!-- 添加或修改工作日志对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body class="dialogStyle" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="125px"
               style="display: grid;grid-template-columns: 1fr 1fr;grid-column-gap: 15px;">
        <el-form-item label="日期" prop="constructDate">
          <el-date-picker v-model="form.constructDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择日期"
                          :picker-options="executeTimeOptions"
                          :disabled="isDatePickerDisabled">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="今日耗时(h)" prop="timeConsume">
          <el-input v-model="form.timeConsume" type="number" placeholder="请输入今日耗时(h)"/>
        </el-form-item>
        <el-form-item label="工作内容">
          <el-input v-model="form.constructContent" type="textarea" placeholder="请输入工作内容" />
        </el-form-item>
        <el-form-item label="遇到的问题及建议" prop="advice">
          <el-input v-model="form.advice" type="textarea" placeholder="请输入遇到的问题及建议"/>
        </el-form-item>
      </el-form>
      <div class="ActionBut">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 日志详情 -->
    <el-dialog :title="workTitle" :visible.sync="openSee" width="850px" append-to-body class="dialogStyle" :close-on-click-modal="false"
               :before-close="cancelSee">
      <div class="ActionBar1" style="min-width: 90px;">
        <!-- 空占位符元素，用于占据 title 区域 -->
        <div style="width: 100%; height: 100%;"></div>
      </div>
      <div class="ActionBar2"> <!-- 修改删除按钮区域 -->
        <el-button plain icon="el-icon-edit" size="mini" @click="handleUpdate" v-hasPermi="['stage:construct:edit']">修改</el-button>
        <el-button plain icon="el-icon-delete" size="mini" @click="handleDelete" v-hasPermi="['stage:construct:remove']">删除</el-button>
      </div>

      <div class="FormContent"> <!-- 表单区域 -->
        <el-form ref="constructionObj">
          <el-form-item  v-for="(row, index) in constructionObj" :key="index" >
            <span :class="[row.userName === nowNickName ? 'current-user' : 'append-textLF']">{{row.userName}}</span>
            <el-input v-model="row.workContentAndAdvice" type="textarea" readonly class="custom-input"/>
            <span class="append-text">今日耗时{{row.timeConsume}}小时</span>
          </el-form-item>
        </el-form>
      </div>

      <div class="ActionBut">
        <el-button @click="cancelSee">关 闭</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import store from '@/store'
import {
  listWorkLog,
  getWorkLog,
  delWorkLog,
  addWorkLog,
  updateWorkLog
} from "@/api/project/construct";
import {
  getInfo,
} from "@/api/project/info";
import Pagination1 from "@/components/Pagination/index1";
import {getUser} from "@/api/system/user";

export default {
  components: {Pagination1},
  name: "Construction",
  data() {
    return {
      // 遮罩层
      loading: true,
      executeTimeOptions: {
        disabledDate: (time) => {
          if (this.sgForm.stepStartDate && this.sgForm.stepEndDate) {
            // console.log(time.getTime(),new Date(this.InfoCardObj.projectStartDate).getTime(), new Date(this.InfoCardObj.projectEndDate).getTime() )
            return time.getTime() > new Date(this.sgForm.stepEndDate).getTime() || time.getTime() + 86400000 < new Date(this.sgForm.stepStartDate).getTime();
          }
        }
      },
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工作日志表格数据
      constructionList: [],
      // 弹出层标题
      title: "",
      // 工作日志标题
      workTitle: "",
      // 是否显示弹出层
      open: false,
      // 是否显示查看页
      openSee: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 13,
        userId: null,
        projectId: null,
        dateArray: []
      },
      // 表单参数
      form: {
        projectId: null
      },
      isDatePickerDisabled: false,
      // 查看详情数组
      constructionObj:[],
      // 施工阶段预设信息
      sgForm: {},
      // 表单校验
      rules: {
        constructDate: [
          {required: true, message: "日期不能为空", trigger: "blur"}
        ],
        timeConsume: [
          { required: true, message: '请输入今日耗时', trigger: 'blur' },
          { validator: this.validateTimeConsume, trigger: 'blur' }
        ],
      },
      queryDate: null,
      nowRowId: null,
      nowNickName : ''
    };
  },
  created() {
    this.queryParams.projectId = this.$route.params.projectId;
    this.form.projectId = this.$route.params.projectId;
    this.getList();
    this.getSgInfo(this.$route.params.projectId);
    this.nowNickName = store.getters.nickName;
  },
  mounted() {
    if (window.innerWidth < 1600) {
      // document.documentElement.style.zoom = "80%";
      document.querySelector('.mainContent').style.zoom = "75%";
    } else if (window.innerWidth > 2200) {
      document.querySelector('.mainContent').style.zoom = "120%";
    }
  },
  methods: {
    getSgInfo(projectId) {
      getInfo(projectId).then(response => {
        if (response.sg) {
          this.sgForm = response.sg;
          console.log("this.sgForm=" , this.sgForm)
        }
      })
    },
    getDefaultDate() {
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, '0');
      const day = String(today.getDate()).padStart(2, '0');

      const formattedDate = `${year}-${month}-${day}`;
      if (this.executeTimeOptions.disabledDate(new Date(today))){
        return '';
      } else {
        this.form.constructDate = formattedDate;
        return formattedDate;
      }
    },
    /** 查询工作日志列表 */
    getList() {
      this.loading = true;
      // console.log("this.queryParams.date=" , this.queryParams.dateArray)
      listWorkLog(this.queryParams).then(response => {
        this.constructionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    validateTimeConsume(rule, value, callback) {
      if (value >= 0 && value <= 24) {
        callback();
      } else {
        callback(new Error('今日耗时必须介于0和24之间'));
      }
    },
    addUnit(row) {
      // 在原始值后面添加 "小时" 后缀
      return row.timeConsume ? row.timeConsume + '小时' : null;
    },
    // 分页连续序号
    indexMethods($index) {
      return (
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize + $index + 1
      );
    },
    //查看按钮操作
    handleSee(row) {
      const id = row.id
      this.nowRowId = id;
      //workLogDetail区
      const construction = this.constructionList.find(construction => construction.id === id);
      // console.log("id= " , id, "constructionObj= ",construction)

      const { userName, constructContent, advice , timeConsumes } = construction;
      const userNameList = userName == null ? [] :userName.split('，');
      const constructContentList = constructContent == null ? [] : constructContent.split("，");
      const adviceList =advice == null ? [] : advice.split('，');
      const timeConsumesList =timeConsumes == null ? [] : timeConsumes.split("，");

      // console.log(userNameList)

      var l = Math.max(userNameList.length,constructContentList.length,adviceList.length,timeConsumesList.length)
      for (let i = 0; i < l; i++) {
        this.constructionObj.push({
          userName: userNameList[i],
          workContentAndAdvice: `  ${constructContentList[i] || ''} \n  遇到的问题及建议: ${adviceList[i] || ''}`,
          timeConsume: timeConsumesList[i]
        });
      }

      this.workTitle = "工作日志-" + construction.constructDate;
      this.queryDate = construction.constructDate;
      // console.log("this.queryDate=" , this.queryDate)
      this.openSee = true;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelSee(){
      this.openSee = false;
      this.isDatePickerDisabled = false;
      this.constructionObj = [];
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        constructDate: null,
        constructContent: null,
        advice: null,
        timeConsume: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getDefaultDate();
      this.open = true;
      this.title = "添加工作日志";
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.reset();
      const id = this.$route.params.projectId;
      getWorkLog(id,this.queryDate).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改工作日志";
        this.isDatePickerDisabled = true; // 禁用日期选项框
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log("this.form=>",this.form)
      this.$refs["form"].validate(valid => {
        this.form.projectId = this.$route.params.projectId;
        if (valid) {
          if (this.form.id != null) {
            updateWorkLog(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.isDatePickerDisabled = false;
              this.getList();
              setTimeout(()=>{
                this.workLogDetail();
              },500)
            });
          } else {
            addWorkLog(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete() {
      const projectId = this.$route.params.projectId;
      this.$modal.confirm('是否确认删除当天的工作日志？').then(()=> {
        return delWorkLog(projectId,this.queryDate);
      }).then(() => {
        this.getList();

        setTimeout(()=>{
          this.workLogDetail();
        },500)

        // console.log("this.constructionObj=" , this.constructionObj)
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    workLogDetail(){
      this.constructionObj = [];
      const  id = this.nowRowId;
      const construction = this.constructionList.find(construction => construction.id === id);

      const { userName, constructContent, advice , timeConsumes } = construction;
      const userNameList = userName.split('，');
      const constructContentList = constructContent.split("，");
      const adviceList = advice.split('，');
      const timeConsumesList = timeConsumes.split("，");

      var l = Math.max(userNameList.length,constructContentList.length,adviceList.length,timeConsumesList.length)
      for (let i = 0; i < l; i++) {
        this.constructionObj.push({
          userName: userNameList[i],
          workContentAndAdvice: `  ${constructContentList[i]} \n  遇到的问题及建议: ${adviceList[i] || ''}`,
          timeConsume: timeConsumesList[i]
        });
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/construction/export', {
        ...this.queryParams
      }, `construction_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss" scoped>@import "~@/assets/styles/InnerInspectionFrame.scss";</style>

<style lang="scss" scoped>
.app-container {
  .main {
    .main2 {
      .mainContent {
        .el-table {
          height: 100%;
        }
      }
    }
  }
}

.current-user {
  color: red;
  position: absolute;
  top: 47%;
  left: 0px;
  font-size: 14px;
  font-family: Microsoft YaHei-Regular, Microsoft YaHei;
  font-weight: 400;
  line-height: 8px;
}
.datePicker {
  display: flex;
  align-items: center;
  margin-left: 20px;
  margin-top: 10px;
}

.FormContent{
  margin-top: 30px;
}


//.custom-label .el-form-item__label {
//  text-align: left !important;
//  vertical-align: middle;
//  float: left;
//  font-size: 14px;
//  color: #606266;
//  line-height: 40px;
//  padding: 0 12px 0 0;
//  -webkit-box-sizing: border-box;
//  box-sizing: border-box;
//}

.append-textLF {
  position: absolute;
  top: 47%;
  left: 0px;
  font-size: 14px;
  font-family: Microsoft YaHei-Regular, Microsoft YaHei;
  font-weight: 400;
  color: #606266;
  line-height: 8px;
}

.append-text {
  position: absolute;
  top: 50%;
  //left: 650px;
  right: 0px;
  transform: translateY(-50%);
  font-size: 16px;
  font-family: Microsoft YaHei-Bold, Microsoft YaHei;
  font-weight: bold;
  color: #606266;
  line-height: 8px;
}

.custom-input {
  width: 550px; /* 自定义输入框的宽度 */
  margin-left: 70px;
}

.pagination-container {
  position: relative;
  height: 30px;
  margin-bottom: 10px;
  margin-top: 15px;
  padding: 10px 20px !important;
}

.enablestatus {
  .dictRed {
    color: #f56c6c;
  }

  .dictBlue {
    color: #1890ff;
  }

  .dictGrey {
    color: #909399;
  }
}
</style>
